package com.mall.controller;

import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.mall.pojo.ResponseMessage;
import com.mall.util.RedisUtil;
import com.mall.util.SmsUtils;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.UUID;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;

/**
 * @author ShouPeng
 * @description
 * @since 2024/1/24
 */
@RestController
@CrossOrigin
public class SmsController {

    @PostMapping("/sendSms/{phoneNumber}")
    @ResponseBody
    public ResponseMessage sendSms( @PathVariable String phoneNumber, HttpServletRequest request){
        String ip = SmsUtils.getIp(request);
        if (RedisUtil.hasKey(phoneNumber+":send")){
            return ResponseMessage.custom("-1","请求太频繁");
        }
        Object o = RedisUtil.get(ip + ":send:count");
        boolean flag = ObjectUtils.isNotEmpty(o);
        if (flag){
            if ((int) o >= 3){
                return ResponseMessage.custom("-1","您每天可接收3次验证码哦");
            }
        }
        if (SmsUtils.checkPhone(phoneNumber)){
            RedisUtil.set(phoneNumber+":send","yes",60);
            String code = ThreadLocalRandom.current().nextInt(100000, 1000000) + "";
            RedisUtil.set(phoneNumber,code,300);
            RedisUtil.incr(ip+":send:count");
            if (!flag){
                RedisUtil.expire(ip + ":send:count",1, TimeUnit.DAYS);
            }
            SmsUtils.sendSms(phoneNumber,code);
            return ResponseMessage.success();
        }
        return ResponseMessage.custom("-1","格式不正确");
    }

    @GetMapping("/sendSms2/{phoneNumber}")
    @ResponseBody
    @ApiOperation("发送手机验证码")
    public void sendSms2(@PathVariable String phoneNumber){
        //System.out.println(123456456);
        SmsUtils.sendSms(phoneNumber,"123456");
    }

}
